﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Sockets;
using System.Threading;
using System.Net;

namespace TCPUtil
{
    public class TCPServerThread
    {
        private int port;
        private Thread _recvThread;
        private bool running;
        private int recvBufferSize = 8192;
        

        public delegate void ProcessTCPMsgDelegation(string msg);
        public ProcessTCPMsgDelegation ProcssTCPMsg;

        public bool Running
        {
            get { return running; }
        }

        public int RecvBufferSize
        {
            get { return recvBufferSize; }
            set { recvBufferSize = value; }
        }


        public TCPServerThread()
        {
        }

        public void Start(int iPort)
        {
            port = iPort;
            _recvThread = new Thread(new ThreadStart(_threadfunc));
            running = true;
            _recvThread.Start();

        }

        public void Stop()
        {

            running = false;
        }

        private void _threadfunc()
        {

            TcpListener listener = new TcpListener(new IPEndPoint(IPAddress.Any, port));
            listener.Start();


            while (running)
            {
                if (listener.Pending())
                {
                    TcpClient remoteClient = listener.AcceptTcpClient();
                    NetworkStream streamToClient = remoteClient.GetStream();
                    byte[] recvBuffer = new byte[recvBufferSize];//buffersize
                    streamToClient.Read(recvBuffer, 0, recvBuffer.Length);
                    string strRecv = Encoding.UTF8.GetString(recvBuffer);
                    strRecv = strRecv.Substring(0, strRecv.IndexOf('\0'));
                    if (ProcssTCPMsg != null)
                    {
                        ProcssTCPMsg(strRecv);
                    }
                    streamToClient.Close();
                    remoteClient.Close();
                }

                else
                {
                    Thread.Sleep(1);
                }
            }
        }
    }
}
